<?php
class App_Source_Media_Handler_Photo extends App_Source_Media_Handler
{
	private $_fileObj;

	protected function InitFile()
	{
		$this->_fileObj = Mozg::Lib('image')->GetImage($this->_filePath);
		if (!$this->_fileObj || !$this->_fileObj->IsImage())
		{
			$this->SetError($this->_fileObj->GetError());
			return;
		}

		$details = $this->_fileObj->GetImageInfo();

		$maxImageSize = Mozg_Cfg::Get('global/media')->GetMaxImageSize();

		if (($maxImageSize[0] < $details[0]) ||
			($maxImageSize[1] < $details[1]))
		{
			$this->SetError(Mozg_Lang::_('MAX_PHOTO_SIZE %x%', $maxImageSize[0], $maxImageSize[1]));
			return;
		}

		$this->_fileSize = $details['filesize'];
		$this->_fileMimeType = $details['mime'];
		$this->_fileLength = $details['0']. 'x' .$details['1'];
	}

	public function CreateThumbNail()
	{
		if (false === $this->_fileThumbNail)
		{
			$this->_fileThumbNail = '';

			$destPath = $this->GetDestPath();
			$fileInfo = pathinfo($this->_filePath);
			$fileThumbNail = $destPath.$fileInfo['filename']. '-thumb.' .$fileInfo['extension'];
			if (copy($this->_filePath, $fileThumbNail))
			{
				$this->_fileThumbNail = $fileThumbNail;
			}
		}

		return $this->_fileThumbNail;
	}

	public function Convert($code)
	{
		$destPath = $this->GetDestPath();
		if (false === $destPath)
		{
			$this->SetConvertStatus(App_Source_Media_Status::HasError);
			$this->SetError(Mozg_Lang::_('ERROR_OCCURED_WHILE_PROCCESSING_FILE'));
			return false;
		}

		$newFileName = pathinfo($this->_filePath, PATHINFO_BASENAME);
		$newFullFileName = $this->_fileObj->Resize($destPath, $newFileName, Mozg_Cfg::Get('global/media')->GetImageSizeTo());

		if ($this->_fileObj->IsError())
		{
			$this->SetConvertStatus(App_Source_Media_Status::HasError);
			$this->SetError($this->_fileObj->GetError());
		    return false;
		}

		$newFilePath = $destPath.$newFullFileName;
		$this->Init($newFilePath);

		$this->SetConvertStatus(App_Source_Media_Status::Ready);

		return $newFilePath;
	}
}